package com.xiaoyu.lanling.feature.push;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;


import com.xiaoyu.base.app.App;
import com.xiaoyu.base.app.AppContext;
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity;
import com.xiaoyu.lanling.feature.main.activity.MainActivity;
import com.xiaoyu.lanling.router.deeplink.DeepLinkRouter;

import in.srain.cube.app.lifecycle.AppActivityLifecycleCallbacks;
import in.srain.cube.request.JsonData;
import in.srain.cube.util.CLog;

public class PushReceiverActivity extends AppCompatToolbarActivity {

    private static final String TAG = "PushReceiverActivity";
    private static final String FCM_ACTION = "LL_PUSH_FCM_RECEIVER";
    private static final String MEIZU_ACTION = "LL_PUSH_MEIZU_RECEIVER";
    private static final String OPPO_ACTION = "LL_PUSH_OPPO_RECEIVER";

    @Override
    protected void onCreateSafelyAfterAppFinishInit(Bundle savedInstanceState) {
        processIntentData(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        processIntentData(intent);
    }

    @Override
    protected boolean isSetRequestedOrientationPortrait() {
        return Build.VERSION.SDK_INT != Build.VERSION_CODES.O;
    }

    private void processIntentData(Intent intent) {
        CLog.d(TAG, "processIntentData %s", intent);
        if (intent == null) {
            finish();
            return;
        }
        if (intent.getAction() != null && (intent.getAction().equals(FCM_ACTION) || intent.getAction().equals(MEIZU_ACTION)
                || intent.getAction().equals(OPPO_ACTION))) {
            final String payloadData = intent.getStringExtra("payload");
            processData(payloadData);
        } else if (intent.getData() != null) {
            final String payloadData = intent.getData().getQueryParameter("payload");
            processData(payloadData);
        } else {
            processRouterUrl("");
        }

        finish();
    }

    private void processData(String payloadData) {
        CLog.d(TAG, "processData %s", payloadData);
        if (!TextUtils.isEmpty(payloadData)) {
            final JsonData payload = JsonData.create(payloadData);
            final String url = payload.optString("url");
            final String pushId = payload.optString("pushId");
            final String eventName = payload.optString("pushOpen");
            final String params = payload.optString("params");

            PushData.getInstance().readPush(pushId, eventName, params);

            processRouterUrl(url);
        } else {
            processRouterUrl("");
        }
    }

    private void processRouterUrl(String url) {
        CLog.d(TAG, "processRouterUrl %s", Uri.decode(url));
        if (isAppLive()) {
            if (!TextUtils.isEmpty(url)) {
                PushData.getInstance().dispatchUrl(this, Uri.decode(url));
            } else {
                openTopActivity();
            }
        } else {
            if (!TextUtils.isEmpty(url)) {
                DeepLinkRouter.getInstance().tryDispatcherPushPendingUri(AppContext.getContext(), Uri.parse(Uri.decode(url)));
            }
            openLaunch();
        }
    }

    private void openLaunch() {
        try {
            final Application application = App.getInstance().getApplication();
            PackageManager packageManager = application.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(application.getPackageName());
            if (intent != null) {
                startActivity(intent);
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    private void openTopActivity() {
        if (AppActivityLifecycleCallbacks.getInstance().isAppInForeground()) {
            return;
        }
        final Activity activity = App.getInstance().getTopActivity();
        if (activity == null) {
            return;
        }
        try {
            Intent intent = new Intent(this, activity.getClass());
            intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    private boolean isAppLive() {
        final Activity activity = App.getInstance().getTopActivity();
        return !(activity == null || activity instanceof PushReceiverActivity || !isMainLive());
    }

    private boolean isMainLive() {
        final String mainClassName = MainActivity.class.getCanonicalName();
        if (mainClassName == null) {
            return false;
        }
        Intent intent = new Intent();
        intent.setClassName(getPackageName(), mainClassName);
        ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return resolveInfo != null;
    }
}
